package epam.marchenko.library.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import epam.marchenko.library.domain.Book;
import epam.marchenko.library.domain.BookClass;
import epam.marchenko.library.domain.OutcomeRecord;
import epam.marchenko.library.domain.User;

@Repository(value="outcomeRecordRepository")
public class OutcomeRecordRepositoryJpaImpl implements OutcomeRecordRepository {
	@PersistenceContext
	private EntityManager em;

	public OutcomeRecordRepositoryJpaImpl() {}

	public OutcomeRecordRepositoryJpaImpl(EntityManager em) {
		this.em = em;
	}

	public OutcomeRecord findById(int id) {
		return em.find(OutcomeRecord.class, id);
	}

	public OutcomeRecord find(OutcomeRecord record) {
		return em.find(OutcomeRecord.class, record.getId());
	}

	public List<OutcomeRecord> findAll() {
		TypedQuery<OutcomeRecord> query = em.createNamedQuery("OutcomeRecord.findAll",
				OutcomeRecord.class);
		return query.getResultList(); 
	}

	@Transactional
	public void create(OutcomeRecord record) {
		  em.persist(record);
	}

	@Transactional
	public void delete(OutcomeRecord record) {
			  em.remove(findById(record.getId()));
	}

	@Transactional
	public void deleteById(int id) {
			  em.remove(findById(id));
	}

	@Transactional
	public void update(OutcomeRecord record) {
			  em.merge(record);
	}


	public List<OutcomeRecord> findForBook(Book book) {
		TypedQuery<OutcomeRecord> query = em.createNamedQuery("OutcomeRecord.findAllForBook",
				OutcomeRecord.class);
		query.setParameter("book", book);
		return query.getResultList(); 
	}

	public List<OutcomeRecord> findForUser(User user) {
		TypedQuery<OutcomeRecord> query = em.createNamedQuery("OutcomeRecord.findAllForUser",
				OutcomeRecord.class);
		query.setParameter("user", user);
		return query.getResultList();
	}

	@Override
	public List<OutcomeRecord> findForClass(BookClass bclass) {
		TypedQuery<OutcomeRecord> query = em.createNamedQuery("OutcomeRecord.findAllForBookClass",
				OutcomeRecord.class);
		query.setParameter("bclass", bclass);
		return query.getResultList();
	}

}
